package se.webbzon.boltzmann.object.escaper;

import java.awt.Component;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import se.webbzon.boltzmann.Main;
import se.webbzon.oschi01.worldarea.WorldArea;
import se.webbzon.oschi01.worldobject.WorldObject;

public class DefaultEscaper extends WorldObject {
	
	// The escape listener of this default escaper
	private final EscapeListener listener;
	
	/*============================================================
	Constructors
	============================================================*/

	public DefaultEscaper() {
		super(WorldObject.onCreate + WorldObject.onDestroy);
		listener = new EscapeListener();
	}

	/*============================================================
	Public Methods
	============================================================*/
	
	/** Escapes to the game menu. **/
	public synchronized void escape() {
		WorldArea world = getWorld();
		if (world != null) {
			world.destroyInstance(this);
			Main.getGameWindow().getEscape().escapeFrom(world);
		}
	}

	@Override public void onCreate(WorldArea world) {
		Window w = Main.getGameWindow();
		w.addWindowListener(listener);
		if (w.getComponentCount() > 0) {
			Component c = w.getComponent(0);
			c.addKeyListener(listener);
		}
	}

	@Override public void onDestroy(WorldArea world) {
		Window w = Main.getGameWindow();
		w.removeWindowListener(listener);
		if (w.getComponentCount() > 0) {
			Component c = w.getComponent(0);
			c.removeKeyListener(listener);
		}
	}
	
	/*============================================================
	Private Classes
	============================================================*/
	
	private final class EscapeListener implements KeyListener, WindowListener {

		@Override public void keyPressed(KeyEvent e) {
			if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
				escape();
			}
		}

		@Override public void keyReleased(KeyEvent e) {};

		@Override public void keyTyped(KeyEvent e) {}

		@Override public void windowActivated(WindowEvent e) {};

		@Override public void windowClosed(WindowEvent e) {};

		@Override public void windowClosing(WindowEvent e) {
			escape();
		}

		@Override public void windowDeactivated(WindowEvent e) {};

		@Override public void windowDeiconified(WindowEvent e) {};

		@Override public void windowIconified(WindowEvent e) {};

		@Override public void windowOpened(WindowEvent e) {};
		
	}
}
